package com.usian.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.common.collect.Maps;
import com.usian.admin.mapper.AdUserMapper;
import com.usian.admin.service.UserLoginService;
import com.usian.common.BaseServiceImpl;
import com.usian.model.admin.dtos.AdUserDto;
import com.usian.model.admin.pojos.AdUser;
import com.usian.model.common.dtos.ResponseResult;
import com.usian.model.common.enums.AppHttpCodeEnum;
import com.usian.utils.common.AppJwtUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import java.util.List;
import java.util.Map;

@Service
@Transactional
public class UserLoginServiceImpl extends BaseServiceImpl<AdUserMapper, AdUser> implements UserLoginService {
    @Override
    public ResponseResult login(AdUserDto dto) {
        if (dto == null)return errorResult;
        if (StringUtils.isBlank(dto.getName())|| StringUtils.isBlank(dto.getPassword()))
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"账号和密码不能为空");
        QueryWrapper<AdUser> wrapper = new QueryWrapper<>();
        wrapper.eq("name",dto.getName());
        List<AdUser> list = list(wrapper);
        if (list !=null && list.size() == 1){
            AdUser adUser = list.get(0);
            String newPwd = DigestUtils.md5DigestAsHex((dto.getPassword() + adUser.getSalt()).getBytes());
            if (newPwd.equals(adUser.getPassword())){
                Map<String, Object> map = Maps.newHashMap();
                adUser.setPassword("");
                adUser.setSalt("");
                map.put("token", AppJwtUtil.getToken(adUser.getId().longValue()));
                map.put("user", adUser);
                return ResponseResult.okResult(map);
            }else {
                return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"密码错误");
            }
        }else return noData;
    }
}
